package h0831;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 字符串解码
 * @date 2024/8/31 16:25
 */
public class DecodeString {
    public static void main(String[] args) {
        String s = "2[a2[c]]";
        System.out.println(decodeString(s));
    }

    public static String decodeString(String s) {
        //一个数字栈，一个结果栈，一个变量存储结果。
        LinkedList<Integer> countStack = new LinkedList<>();
        LinkedList<String> resultStack = new LinkedList<>();
        String res = "";
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (Character.isDigit(ch)) {
                int start = i;
                while (Character.isDigit(s.charAt(i))) {
                    i++;
                }
                countStack.addLast(Integer.parseInt(s.substring(start, i)));
                i--;
            } else if (ch == '[') {
                resultStack.addLast(res);
                res = "";
            } else if (ch == ']') {
                StringBuilder builder = new StringBuilder();
                int n = countStack.removeLast();
                //从结果栈中弹出部分结果。
                String temp = resultStack.removeLast();
                for (int j = 0; j < n; j++) {
                    builder.append(res);
                }
                res = temp + builder;
            } else {
                res += ch;
            }
        }

        return res;
    }
}
